package com.test.platform.controller;

import com.test.platform.model.Project;
import com.test.platform.service.Project.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
@RequestMapping("/api/projects")
public class ProjectController {
    private static final Logger logger = LoggerFactory.getLogger(ProjectController.class);

    @Autowired
    private ProjectService projectService;
    
    @GetMapping
    public ResponseEntity<List<Project>> getAllProjects() {
        return ResponseEntity.ok(projectService.getAllProjects());
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Project> getProjectById(@PathVariable Integer id) {
        Project project = projectService.getProjectById(id);
        if (project != null) {
            return ResponseEntity.ok(project);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    
    @GetMapping("/search/owner")
    public ResponseEntity<List<Project>> getProjectsByOwner(
            @RequestParam String owner) {
        List<Project> projects = projectService.getProjectsByOwner(owner);
        return ResponseEntity.ok(projects);
    }

    @GetMapping("/search/name")
    public ResponseEntity<List<Project>> getProjectsByName(
            @RequestParam String name) {
        List<Project> projects = projectService.getProjectsByName(name);
        return ResponseEntity.ok(projects);
    }

    // 修改现有的搜索接口
    @GetMapping("/search")
    public ResponseEntity<List<Project>> getProjectsByOwnerAndName(
            @RequestParam(required = false) String owner,
            @RequestParam(required = false) String name) {
        List<Project> projects;
        if (owner != null && name != null) {
            projects = projectService.getProjectsByOwnerAndName(owner, name);
        } else if (owner != null) {
            projects = projectService.getProjectsByOwner(owner);
        } else if (name != null) {
            projects = projectService.getProjectsByName(name);
        } else {
            projects = projectService.getAllProjects();
        }
        return ResponseEntity.ok(projects);
    }

    @PostMapping("/update")
    public ResponseEntity<?> updateProjectInfo(@RequestBody Project project) {
        try {
            boolean result = projectService.updateProject(project);
            if (result) {
                return ResponseEntity.ok().body(Map.of("message", "项目更新成功"));
            } else {
                return ResponseEntity.badRequest().body(Map.of("message", "项目更新失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("message", "服务器错误：" + e.getMessage()));
        }
    }

    @PostMapping("/refresh")
    public ResponseEntity<?> refreshProjects() {
        try {
            projectService.initializeProjectsFromJson();
            return ResponseEntity.ok().body(Map.of("message", "项目信息刷新成功"));
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("message", "刷新失败：" + e.getMessage()));
        }
    }

    @PostMapping
    public ResponseEntity<?> createProject(@RequestBody Project project) {
        try {
            boolean result = projectService.createProject(project);
            if (result) {
                return ResponseEntity.ok().body(Map.of("message", "项目创建成功"));
            } else {
                return ResponseEntity.badRequest().body(Map.of("message", "项目创建失败"));
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body(Map.of("message", "服务器错误：" + e.getMessage()));
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateProject(@PathVariable Integer id, @RequestBody Project project) {
        project.setId(id);
        boolean result = projectService.updateProject(project);
        if (result) {
            return ResponseEntity.ok().body(Map.of("message", "项目更新成功"));
        } else {
            return ResponseEntity.badRequest().body(Map.of("message", "项目更新失败"));
        }
    }  // 添加缺失的大括号
    
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteProject(@PathVariable Integer id) {
        try {
            logger.info("接收到删除项目请求: id={}", id);
            boolean result = projectService.deleteById(id);
            if (result) {
                return ResponseEntity.ok().body(Map.of(
                    "success", true,
                    "message", "删除成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "删除失败"
                ));
            }
        } catch (Exception e) {
            logger.error("删除项目时发生错误", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "删除失败: " + e.getMessage()
            ));
        }
    }

    @DeleteMapping("/batch")
    public ResponseEntity<?> batchDeleteProjects(@RequestBody List<Integer> ids) {
        try {
            logger.info("接收到批量删除项目请求: ids={}", ids);
            boolean result = projectService.deleteByIds(ids);
            if (result) {
                return ResponseEntity.ok().body(Map.of(
                    "success", true,
                    "message", "批量删除成功"
                ));
            } else {
                return ResponseEntity.badRequest().body(Map.of(
                    "success", false,
                    "message", "批量删除失败"
                ));
            }
        } catch (Exception e) {
            logger.error("批量删除项目时发生错误", e);
            return ResponseEntity.internalServerError().body(Map.of(
                "success", false,
                "message", "批量删除失败: " + e.getMessage()
            ));
        }
    }
}
